import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provide/provide.dart';
import './person.dart';

class CartProvide with ChangeNotifier {
  String cartString = "[]";// 这个购物车信息用来持久化
  List cartList = [];// 这个用来展示
  double allPrice = 0 ;   //总价格
  String allPriceString = ''; // 保留两位小数的总价格
  int allGoodsCount = 0;  //商品总数量
  bool isAllCheck= true; //是否全选

  //得到购物车中的商品
  getCartInfo() async {
     SharedPreferences prefs = await SharedPreferences.getInstance();
     //获得购物车中的商品,这时候是一个字符串
     cartString=prefs.getString('cartInfo'); 
     //把cartList进行初始化，防止数据混乱 
     cartList=[];
     //判断得到的字符串是否有值，如果不判断会报错
     if(cartString==null){
       cartList=[];
     }else{
       List<Map> tempList= (json.decode(cartString.toString()) as List).cast();
       allPrice=0;
       allGoodsCount=0;
       isAllCheck = true;
       tempList.forEach((item){
         // 计算价格
         if(item['isCheck']){
             allPrice+=(item['count']*item['price']);
             allGoodsCount+=item['count'];
          }else {
            isAllCheck = false;
          }
          cartList.add(item);
       });
      allPriceString = allPrice.toStringAsFixed(2);
     }
      notifyListeners();
  }

  // 添加商品到购物车
  save(goodsId,goodsName,count,price,images,context) async {
    // 初始化 sharedPreferences
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    // 判断 cartString 是否为空，为空说明是第一次添加的，或者 key 被清除了
    var temp = cartString == null ? [] : json.decode(cartString.toString());
    // 转为 List
    List<Map> tempList = (temp as List).cast();
    // 声明变量，用于判断购物车中是否已经存在此商品ID
    var isHave = false;// 默认没有
    int ival = 0;// 循环索引值
    int index = 0;
    tempList.forEach((item){
      if(item['goodsId']==goodsId){
        index = ival;
        cartList[ival]['count']++;
        isHave = true;
      }
      ival++;
    });
    
    if(!isHave){
      Map<String, dynamic> newGoods={
          'goodsId':goodsId,
        'goodsName':goodsName,
        'count':count,
        'price':price,
        'images':images,
        'isCheck':true
      };
      tempList.add(newGoods);
      cartList.add(newGoods);
      Fluttertoast.showToast(
        msg: '商品添加成功',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
      );
  }else {
    tempList[index]['count'] +=1;
    Fluttertoast.showToast(
      msg: '购物车已有此商品，数量加1',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Theme.of(context).primaryColor,
      textColor: Colors.white,
      fontSize: 16.0
    );
  }
  allGoodsCount=0;
  allPrice = 0;
  tempList.forEach((item){
    if(item['isCheck']){
      allPrice += item['count'] * item['price'];
      allGoodsCount += item['count'];
    }
  });
  allPriceString = allPrice.toStringAsFixed(2);
  //把字符串进行encode操作，
  cartString= json.encode(tempList).toString();
  prefs.setString('cartInfo', cartString);//进行持久化
  notifyListeners();
  }

  // 清空购物车
  remove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('cartInfo');
    cartList = [];
    cartString = '';
    allPrice = 0;
    allGoodsCount = 0;
    allPriceString = '';
    notifyListeners();
  }

  //删除单个购物车商品
  deleteOneGoods(String goodsId) async{
     SharedPreferences prefs = await SharedPreferences.getInstance();
     cartString=prefs.getString('cartInfo'); 
     List<Map> tempList= (json.decode(cartString.toString()) as List).cast();
   
     int tempIndex =0;
     int delIndex=0;
     tempList.forEach((item){
         
         if(item['goodsId']==goodsId){
          delIndex=tempIndex;
        
         }
         tempIndex++;
     });
      // 删除指定商品
      tempList.removeAt(delIndex);
      cartString= json.encode(tempList).toString();
      // 存储持久化数据
      prefs.setString('cartInfo', cartString);
      // 重新获得持久化数据
      await getCartInfo();
  }

  //  改变商品选择状态
  changeCheckState(cartItem) async{
     SharedPreferences prefs = await SharedPreferences.getInstance();
     cartString=prefs.getString('cartInfo');  //得到持久化的字符串
     List<Map> tempList= (json.decode(cartString.toString()) as List).cast(); //声明临时List，用于循环，找到修改项的索引
     int tempIndex =0;  //循环使用索引
     int changeIndex=0; //需要修改的索引
     tempList.forEach((item){
         if(item['goodsId']==cartItem['goodsId']){
          //找到索引进行复制
          changeIndex=tempIndex;
         }
         tempIndex++;
     });
     tempList[changeIndex]=cartItem; //把对象变成Map值
     cartString= json.encode(tempList).toString(); //变成字符串
     prefs.setString('cartInfo', cartString);//进行持久化
     await getCartInfo();  //重新读取列表
    
  }

  //点击全选按钮操作
  changeAllCheckBtnState(bool isCheck) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo'); 
    List<Map> tempList= (json.decode(cartString.toString()) as List).cast(); 
    List<Map> newList=[]; //新建一个List，用于组成新的持久化数据。
    for(var item in tempList ){
      var newItem = item; //复制新的变量，因为Dart不让循环时修改原值
      newItem['isCheck']=isCheck; //改变选中状态
      newList.add(newItem);
    } 
   
     cartString= json.encode(newList).toString();//形成字符串
     prefs.setString('cartInfo', cartString);//进行持久化
     await getCartInfo();

  }

  // 点击商品数量加减按钮
  addOrReduceAction(cartItem, String todo )async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo'); 
    List<Map> tempList= (json.decode(cartString.toString()) as List).cast();
    int tempIndex =0;
    int changeIndex=0;
    tempList.forEach((item){
         if(item['goodsId']==cartItem['goodsId']){
          changeIndex=tempIndex; 
         }
         tempIndex++;
     });
     if(todo=='add'){
       cartItem['count']++;
     }else if(cartItem['count']>1){
       cartItem['count']--;
     }
     tempList[changeIndex]=cartItem;
     cartString= json.encode(tempList).toString();
     prefs.setString('cartInfo', cartString);//
     await getCartInfo();
  }

  // 点击提交订单
  void postCart(token,userName,context)async {
    List postList = [];// 临时存储要提交的商品
    // 要判断商品是不是选中的状态
    cartList.forEach((item){
      if(item['isCheck']){
        postList.add(item);
      }
    });
    Dio dio = new Dio();
    Options options = Options(
      headers: {HttpHeaders.authorizationHeader : token},
      contentType: ContentType.parse("application/x-www-form-urlencoded")
    );
    dio.interceptors.add(InterceptorsWrapper(
      onRequest:(RequestOptions options){
        // 在请求被发送之前做一些事情
        print('被发送之前');
        return options; //continue
        },
        onResponse:(Response response) {
        // 在返回响应数据之前做一些预处理
        print("响应之前");
        // print(response.headers);
        return response; // continue
        },
        onError: (DioError e) {
          // 当请求失败时做一些预处理
          print('请求失败了');
          // print(e.response.data);
          if(e.response.statusCode==401){
            Fluttertoast.showToast(
              msg: '登录过期，请重新登录',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIos: 1,
              backgroundColor: Theme.of(context).primaryColor,
              textColor: Colors.white,
              fontSize: 16.0
            );
            Provide.value<PersonnalProvider>(context).out();
          }
          print(e.response.statusCode);
        return e;//continue
        }
    ));
    var formData = {
      'userName': userName,
      'cart': postList
    };
    Response response = await dio.post('http://dianshan.free.idcfengye.com/goods/postCart',options: options,data: formData);
    var data = json.decode(response.toString());
    Fluttertoast.showToast(
      msg: data['message'],
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
      backgroundColor: Theme.of(context).primaryColor,
      textColor: Colors.white,
      fontSize: 16.0
    );
  }
}